<template>
  <div class="rechargeOrderMana-container common-container">
    <div class="common-top">
      <span class="left">
        <!--拼团订单信息-->
        <el-form
          :inline="true"
          :model="formInline"
          size="small"
          class="demo-form-inline"
        >
        <el-form-item label="搜索">
        <el-input
          v-model="formInline.searchVal"
          placeholder="搜索"
        ></el-input>
        </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="statuses" multiple placeholder="请选择">
                    <el-option
                      v-for="item in statusOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
        </el-select>

            </el-form-item>
          <el-form-item label="">
             <el-date-picker
               v-model="timeArr"
               type="datetimerange"
               range-separator="至"
               :default-time="['00:00:00', '23:59:59']"
               start-placeholder="开始日期"
               end-placeholder="结束日期"
               :picker-options="pickerOptions"
             ></el-date-picker>
            </el-form-item>
      <el-button
        type="primary"
        style="margin-left: 10px"
        @click.stop="getData"
      >查询
      </el-button>
        </el-form>
      </span>
      <JsonExcel :fetch="fetchAllData"
                 :fields="excel_fields"
                 :before-generate="startDownload"
                 :before-finish="finishDownload"
                 name="待发货订单.xls">
        <el-button type="primary">导出待发货订单</el-button>
      </JsonExcel>
      <el-upload
        action="12312"
        style="margin-left: 10px"
        class="upload-demo"
        :show-file-list="false"
        :on-change="handlePreview">
        <el-button type="primary">导入发货订单</el-button>
      </el-upload>
    </div>
    <div class="common-bot">
      <el-table :data="tableData" id='out-table' style="width: 100%">
        <el-table-column prop="source" label="订单号" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="购买者" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.creator">
              {{ scope.row.creator.name }}
              <span v-if="scope.row.creator.inviteUser"><br>(邀请人：{{scope.row.creator.inviteUser.name}})</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="加入时间" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.creator">{{ scope.row.creator.createTime | parseTime }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="产品名称" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.productName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="订单金额" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.money | parseMoneyExcept }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="收货人信息" align="center">
          <template slot-scope="scope">
            <div>
              <div>{{ scope.row.name }}</div>
              <div>{{ scope.row.mobile }}</div>
              <div>{{ scope.row.address }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="物流信息" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.expressName">
              <div>{{ scope.row.expressName }}</div>
              <div>{{ scope.row.expressNumber }}</div>
            </div>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime | parseTime }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="状态" align="center">
          <template slot-scope="scope">
            <span>
              {{ statusFormat[scope.row.status] }}<br>
              <span v-if="scope.row.status == 'refund'"
                    style="color: red">奖金：￥{{scope.row.reward | parseMoneyExcept}}</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="中签状态" align="center">
          <template slot-scope="scope">
            <span :class="{'red':scope.row.bingo}">{{ bingoFormat[scope.row.bingo] }}</span>
          </template>
        </el-table-column>
        <!--<el-table-column prop="source" label="支付方式" align="center">-->
        <!--<template slot-scope="scope">-->
        <!--<span>{{ payTypeFormat[scope.row.payType] }}</span>-->
        <!--</template>-->
        <!--</el-table-column>-->
        <el-table-column label="支付时间" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.payTime>0">{{ scope.row.payTime | parseTime }}</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center"
                         v-if="hasPerm('orders:user:express') || hasPerm('orders:user:detail')">
          <template slot-scope="scope">
            <span @click='goPopup(scope.row)' v-if="scope.row.status==='grouped' && hasPerm('orders:user:express')"
                  style="cursor: pointer;color: red;margin-right: 10px">发货</span>
            <span @click='goChangeInfoPopup(scope.row)'
                  v-if="hasPerm('orders:user:express')&&scope.row.status==='shipped'"
                  style="cursor: pointer;color: red;margin-right: 10px">修改物流信息</span>
            <span class="span-modify edit" v-if="hasPerm('orders:user:detail')"
                  @click.stop="openDetailDialog(scope.row)">详情</span>
          </template>
        </el-table-column>


      </el-table>
      <div class="pagination">
        <el-pagination
          v-if="showPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="nowPage"
          :page-size="limit"
          layout="total, prev, pager, next"
          :total="totalElement"
        ></el-pagination>
      </div>
    </div>
    <!--发货-->
    <el-dialog
      :visible.sync="orderExpressVisible"
      width="30%"
      :before-close="handleClose">
      <el-form ref="form" label-position='left' label-width="100px">
        <el-form-item label="快递公司">
          <el-select
            v-model="orderExpressParams.expressName"
            filterable
            allow-create
            default-first-option
            placeholder="请选择或输入快递公司">
            <el-option
              v-for="item in expressOptions"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="快递单号">
          <el-input v-model="orderExpressParams.expressNumber" placeholder="请输入快递单号"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="orderExpressVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureExpress">确 定</el-button>
      </span>
    </el-dialog>
    <!--修改物流信息-->
    <el-dialog
      :visible.sync="changeInfoVisible"
      width="30%"
      :before-close="handleClose">
      <el-form ref="form" label-position='left' label-width="100px">
        <el-form-item label="快递公司">
          <el-select
            v-model="changeInfoParams.expressName"
            filterable
            allow-create
            default-first-option
            placeholder="请选择或输入快递公司">
            <el-option
              v-for="item in expressOptions"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
          <!--<el-input v-model="changeInfoParams.expressName"></el-input>-->
        </el-form-item>
        <el-form-item label="快递单号">
          <el-input v-model="changeInfoParams.expressNumber" placeholder="请输入快递单号"></el-input>
          <!--<el-input v-model="changeInfoParams.expressNumber"></el-input>-->
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="changeInfoVisible = false">取 消</el-button>
        <el-button type="primary" @click="changeInformation" v-if="hasPerm('orders:recharge:express')">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="订单详情" :visible.sync="detailsDialogTableVisible">
      <table class="detailsTable" :data="detailsGridData">
        <tr>
          <td>收货人：</td>
          <td>
            <div class="content">{{detailsGridData.name}}</div>
          </td>
        </tr>
        <tr>
          <td>电话：</td>
          <td>
            <div class="content">{{detailsGridData.mobile}}</div>
          </td>
        </tr>
        <tr>
          <td>地址：</td>
          <td>
            <div class="content">{{detailsGridData.address}}</div>
          </td>
        </tr>
        <tr>
          <td>备注：</td>
          <td>
            <div class="content">{{detailsGridData.remark}}</div>
          </td>
        </tr>
        <tr v-if="detailsGridData.expressName">
          <td>运单公司：</td>
          <td>
            <div class="content">{{detailsGridData.expressName}}</div>
          </td>
        </tr>
        <tr v-if="detailsGridData.expressNumber">
          <td>运单号：</td>
          <td>
            <div class="content">{{detailsGridData.expressNumber}}</div>
          </td>
        </tr>

        <tr class="interval">
          <td colspan="2"></td>
        </tr>
      </table>

    </el-dialog>
    <el-dialog title="发货清单导入" :visible.sync="expressDialogVisible" id="express_dialog" width="90%">
      <el-table :data="expressOrders" style="width: 100%;">
        <el-table-column prop="source" label="订单号" align="center">
          <template slot-scope="scope">
            <span>{{ expressNumber(scope.row['订单号']) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="产品名称" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row['产品名称'] }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="收货人" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row['收货人'] }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="电话" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row['电话'] }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="地址" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row['地址'] }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="快递公司" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row['快递公司'] }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="快递单号" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row['快递单号'] }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="状态" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.error" style="color: red">{{ scope.row.status ? scope.row.status : '待处理' }}</span>
            <span v-else>{{ scope.row.status ? scope.row.status : '待处理' }}</span>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="danger" @click="expressDialogVisible = false" v-if="expressSubmitSuccess">导入完毕，点击关闭</el-button>
        <el-button type="primary" @click="expressConfirm"
                   :loading="expressSubmitting" v-else>{{expressSubmittingText}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import XLSX from 'xlsx'
  import {mapGetters} from "vuex";
  import {groupbuyOrderExpress, groupbuyOrderList} from "@/api/order";
  import {parseTime} from '@/utils'
  import {Loading} from 'element-ui';

  export default {
    name: "rechargeOrder",
    computed: {
      ...mapGetters(["name"]),
    },
    data() {
      return {
        expressOptions: ['自提', '跨越速运', '顺丰速运', '邮政快递', '高铁速递', '宅急送', '中通快递', '圆通速递', '申通快递', '百世快递', '韵达快递', '国通快递', '天天快递', '快捷速递', '速尔快递', '全峰快递', '全一快递', '大亿快递', '如风达', '能达快递', '德邦物流', '优速快递', '京东快递'],
        pickerOptions: {
          shortcuts: [
            {
              text: "最近一周",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit("pick", [start, end]);
              },
            },
            {
              text: "最近一个月",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit("pick", [start, end]);
              },
            },
            {
              text: "最近三个月",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                picker.$emit("pick", [start, end]);
              },
            },
          ],
        },
        createUserTypeOptions: {
          manager: "管理员",
          teacher: "导师",
          user: "用户",
        },
        bingoFormat: {
          true: "已中签",
          false: "未中签",
        },
        showOrderInfo: false,
        showPage: false,
        orderExpressVisible: false,
        changeInfoVisible: false,
        detailsDialogTableVisible: false,
        orderExpressParams: {   //发货
          targetId: '',
          expressName: '',
          expressNumber: '',
        },
        changeInfoParams: {   //修改物流信息
          targetId: '',
          expressName: '',
          expressNumber: '',
        },
        formInline: {
          searchVal: "",
        },
        statuses: [],
        orderList: [],
        timeArr: ["", ""],
        detailsGridData: {},
        excel_fields: {
          "订单号": "orderId",
          "产品名称": "productName",
          "收货人": "name",
          "电话": "mobile",
          "地址": "address",
          "下单时间": "createTimeFormat",
          "快递公司": "null",
          "快递单号": "null",
        },
        tableData: [],
        payTypeFormat: {
          wxpay_online: "微信",
          alipay: "支付宝",
        },
        statusOptions: [
          {
            value: 'cancel',
            label: '已取消',
          }, {
            value: 'init',
            label: '待付款',
          }, {
            value: 'paid',
            label: '待成团',
          }, {
            value: 'grouped',
            label: '待发货',
          }, {
            value: 'shipped',
            label: '待收货',
          }, {
            value: 'finish',
            label: '已完成',
          }, {
            value: 'refund',
            label: '已退款',
          },
        ],
        statusFormat: {
          cancel: "已取消",
          init: "待付款",
          paid: "待成团",
          grouped: "待发货",
          shipped: "待收货",
          finish: "已完成",
          refund: "已退款",
        },
        limit: 10,
        limitForOrder: 10,
        nowPageForOrder: 1,
        nowPage: 1,
        totalElement: 0,
        totalElementForOrder: 0,
        gender: {
          female: "女",
          male: "男",
        },
        checkStatusOptions: {
          checking: "审核中",
          success: "审核通过",
          failed: "未通过",
        },
        loadingInstance: null,
        expressOrders: [],
        expressDialogVisible: false,
        expressSubmitting: false,
        expressSubmittingText: '确定导入',
        expressSubmitSuccess: false,
      };
    },
    watch: {
      nowPage(val) {
        this.getData();
        this.setStateData(val);
      },
      limit(val) {
        this.getData();
      },
      statuses(val) {
        this.getData();
      },
      "formInline.searchVal": function (val) {
        this.getData();
      },
    },
    methods: {
      beginTime(year, month) {
        if (month.length <= 1) {
          let month = "0" + month;
        }
        let startTime = year + "-" + month + "-" + "01" + " 00:00:00";
        // return new Date(startTime).getTime() ;
        return startTime;
      },
      getDayDiff(s1, s2) {
        let days = new Date(s2).getTime() - new Date(s1).getTime();
        let time = parseInt(days / (1000 * 60 * 60 * 24)) + 1;
        return time;
      },
      lastTime(year, month) {
        if (month.length <= 1) {
          let month = "0" + month;
        }
        let day = new Date(year, month, 0);
        let lastdate = year + "-" + month + "-" + day.getDate();
        let lastTime = lastdate + " 23:59:59";
        // return new Date(lastTime).getTime() ;
        return lastTime;
      },
      formatTime() {
        let dayCount = this.getDayDiff(this.timeArr[0], this.timeArr[1]);

        let start = new Date(this.timeArr[0]).Format("yyyy/MM/dd");
        let last = new Date(this.timeArr[1]).Format("yyyy/MM/dd");
        start = new Date(start).getTime();
        last = new Date(last).getTime();
        let day = 1000 * 60 * 60 * 24;
        let xData = [];
        for (let i = 0; i < dayCount; i++) {
          let time = new Date(Number(start) + day * i).Format("yyyy/MM/dd");
          xData.push(time);
        }
        return xData;
      },
      setStateData(nowPage) {
        let stateData = {
          nowPage,
        };
        this.$router.replace({
          path: this.$route.path,
          query: {
            stateData: this.$base64.encode(JSON.stringify(stateData)),
          },
        });
      },
      goPopup(item) {
        this.orderExpressVisible = true;
        console.log(item, "点击发货");
        this.orderExpressParams.targetId = item.id;
      },
      //点击修改物流信息popup
      goChangeInfoPopup(item) {
        this.changeInfoVisible = true;
        console.log(item, "修改物流信息");
        this.changeInfoParams = {   //修改物流信息
          targetId: item.id,
          expressName: item.expressName,
          expressNumber: item.expressNumber,
        }
      },
      //点击发货
      sureExpress() {
        this.orderExpressVisible = false;
        groupbuyOrderExpress(this.orderExpressParams)
          .then((res) => {
            if (res.code === 200) {
              this.$message({
                message: '发货成功!',
                type: 'success'
              })
              this.getData();
            } else {
              this.$message({
                message: res.message,
                type: 'error'
              })
            }
          });
      },
      //修改物流信息
      changeInformation() {
        this.changeInfoVisible = false;
        groupbuyOrderExpress(this.changeInfoParams)
          .then((res) => {
            if (res.code === 200) {
              this.$message({
                message: '修改物流信息成功!',
                type: 'success'
              })
              this.getData();
            } else {
              this.$message({
                message: res.message,
                type: 'error'
              })
            }
          });
      },
      openDetailDialog(item) {
        this.detailsDialogTableVisible = true
        console.log(item, "点击拼团订单详情");
        this.detailsGridData = item
      },

      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.limit = val;
      },
      handleCurrentChange(val) {
        this.nowPage = val;
      },
      handleClose(done) {
        done();
      },
      toModify(type) {
        this.$router.push({name: "ModifyTeacher", query: {type}});
      },
      async fetchAllData() {
        let orders = []
        let page = 0

        while (true) {
          let res = await groupbuyOrderList({
            statuses: ['grouped'],
            limit: 50,
            page: page++
          });
          res.data.forEach((item, index) => {
            item.orderId = item.id + ','
            item.createTimeFormat = parseTime(item.createTime)
          })
          orders = orders.concat(res.data)
          if (res.data.length < 50) {
            break
          }
        }
        return orders;
      },
      startDownload() {
        this.loadingInstance = Loading.service({fullscreen: true, text: '正在处理中...'});
      },
      finishDownload() {
        if (this.loadingInstance) {
          this.loadingInstance.close()
          this.loadingInstance = null
        }
      },
      handlePreview(file, files) {
        this.startDownload()
        this.expressOrders = []
        this.expressSubmitting = false
        this.expressSubmitSuccess = false
        this.expressSubmittingText = '确认导入'
        var fileReader = new FileReader();
        fileReader.onload = (ev) => {
          console.log(ev, 'ev')
          try {
            var data = ev.target.result,
              workbook = XLSX.read(data, {
                type: 'binary'
              }), // 以二进制流方式读取得到整份excel表格对象
              orders = []; // 存储获取到的数据
          } catch (e) {
            console.log('文件类型不正确');
            return;
          }
          // 表格的表格范围，可用于判断表头是否数量是否正确
          var fromTo = '';
          // 遍历每张表读取
          for (var sheet in workbook.Sheets) {
            if (workbook.Sheets.hasOwnProperty(sheet)) {
              fromTo = workbook.Sheets[sheet]['!ref'];
              console.log(fromTo);
              orders = orders.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
              // break; // 如果只取第一张表，就取消注释这行
            }
          }
          console.log(orders);
          this.finishDownload()
          this.expressOrders = orders
          this.expressDialogVisible = true
        };
        // 以二进制方式打开文件
        fileReader.readAsBinaryString(file.raw);
      },
      expressNumber(str) {
        if (str.indexOf(",") == -1) return null
        return str.substr(0, str.indexOf(","))
      },
      expressConfirm() {
        this.expressSubmitting = true
        this.expressSubmittingText = '正在导入，请不要关闭窗口...'

        this.executeExpressImport()
      },
      async executeExpressImport() {
        for (let i = 0; i < this.expressOrders.length; i++) {
          let item = this.expressOrders[i]
          if (!item['订单号'] || !item['快递公司'] || !item['快递单号']) {
            item.error = true
            item.status = '快递信息不完整，请完善表格'
          } else {
            try {
              let res = await groupbuyOrderExpress({
                targetId: this.expressNumber(item['订单号']),
                expressName: item['快递公司'],
                expressNumber: item['快递单号']
              })
              if (res.code == 200) {
                item.status = '提交成功'
              } else {
                item.error = true
                item.status = '提交失败:' + res.message
              }
            } catch (e) {
              item.error = true
              item.status = '提交失败'
            }
          }

          this.$set(this.expressOrders[i], item)
        }
        this.expressSubmitSuccess = true
      },
      getData() {
        if (!this.timeArr || !this.timeArr.length || !this.timeArr[0]) {
          this.$message.error("请选择时间");
          return;
        }
        let dayCount = this.getDayDiff(this.timeArr[0], this.timeArr[1]);
        groupbuyOrderList({
          startTime: new Date(this.timeArr[0]).getTime(),
          endTime: new Date(this.timeArr[1]).getTime(),
          keyword: this.formInline.searchVal,
          statuses: this.statuses,
          limit: this.limit,
          page: this.nowPage - 1
        })
          .then((res) => {
            if (res.code === 200) {
              console.log(res, "groupbuyOrderList拼团8888");
              this.tableData = res.data;
              this.totalElement = res.total;
              this.showPage = true;
            }
          });
      },
    },
    mounted() {
      let year = new Date().getFullYear();
      let month = new Date().getMonth() + 1;

      this.timeArr = [this.beginTime(year, month), this.lastTime(year, month)];
      this.getData();
    },
  };
</script>

<style lang="scss" scoped>
  .detailsTable {
    tr {
      line-height: 20px;
      td:first-child {
        text-align: right;
      }
    }

  }

  .el-form-item {
    /*border: 1px solid  red;*/
    /*height: 40px;*/
    /*display: flex;*/
  }
</style>
<style>
  #express_dialog .el-dialog .el-dialog__body {
    height: 300px;
    overflow-y: scroll;
  }
</style>
